<template>
  <div class="order-confirm-container">
    <div class="header-panel">
        <h2>订单确认</h2>
        <button @click="router.push('/booking')" class="booking-btn">返回</button>
    </div>
    <div class="order-info">
      <h3>会议室：{{ selectedRoom.room_name }}</h3>
      <p>类型：{{ selectedRoom.room_type }}</p>
      <p>使用时间：{{ formatTime(startTime) }} 至 {{ formatTime(endTime) }}</p>
      <p>参会人数：{{ participantNum }}人</p>
      <p>设备：{{ deviceList }}</p>
      <p>单价：{{ selectedRoom.price_per_hour }}元/小时</p>
      <p>总时长：{{ durationHours }}小时</p>
      <p>总价：{{ totalPrice }}元</p>
    </div>
    
    <div v-if="isLocked" class="payment-timer">
        <p>请在 {{ remainingTime }} 内完成支付，否则订单将自动取消</p>
    </div>
    
    <button @click="handlePayment" :disabled="!isLocked">立即支付</button>
    <p v-if="!isLocked">订单状态：{{ orderStatus }}</p>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import axios from '../axios';
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../store/UserStore';
import { useWebSocketStore } from '../store/WebSocketStore';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const selectedRoom = ref({});
const startTime = ref('');
const endTime = ref('');
const participantNum = ref(1);

const isLocked = ref(false); // 是否锁定
const orderStatus = ref(''); // 订单状态
const countdown = ref(30 * 60); // 倒计时（秒）
const orderId = ref(null); // 订单ID
let timer = null;

const remainingTime = ref('00:00');
let countdownTimer = null;

const createdTime = ref(null); // 订单创建时间

const handleOrderUpdated = (payload) => {
  if (payload.orderId === orderId.value) {
    orderStatus.value = payload.status;
    isLocked.value = payload.status === '锁定';
  }
};

onMounted(() => {
  const wsStore = useWebSocketStore();
  wsStore.on('server:order-updated', handleOrderUpdated);
});

onUnmounted(() => {
  const wsStore = useWebSocketStore();
  wsStore.off('server:order-updated', handleOrderUpdated);
});

// 计算设备列表
const deviceList = computed(() => {
  const devices = [];
  if (selectedRoom.value.has_projector) devices.push('投影仪');
  if (selectedRoom.value.has_sound) devices.push('音响');
  if (selectedRoom.value.has_internet) devices.push('网络');
  return devices.join(', ') || '无';
});

// 计算时长（小时）
const durationHours = computed(() => {
  const start = new Date(startTime.value);
  const end = new Date(endTime.value);
  return Math.max(0, Math.round((end - start) / (1000 * 60 * 60)));
});

const pricePerHour = computed(() => {
  return selectedRoom.value.price_per_hour || 0;
});

// 计算总价
const totalPrice = computed(() => {
  const hours = durationHours.value;
  const price = parseFloat(pricePerHour.value);
  return (hours * price).toFixed(2);
});

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});

onMounted(async () => {
  const { roomId, startTime: st, endTime: et, participantNum: pn, orderId: oid } = route.query;

  if (!st || !et || !pn || !oid) {
    alert('缺少必要参数，请重新操作');
    return;
  }

  startTime.value = st;
  endTime.value = et;
  participantNum.value = parseInt(pn);
  orderId.value = oid;

  await fetchRoomDetails(roomId);

  try {
    const res = await axios.get(`/orders/${orderId.value}`);
    const order = res.data.data;

    isLocked.value = order.order_status === '锁定';
    orderStatus.value = order.order_status;

    const createTimeStr = order['create_time'];
    if (createTimeStr) {
      createdTime.value = new Date(createTimeStr);
    }

    // 启动倒计时
    startCountdown();

  } catch (error) {
    alert('加载订单失败');
    console.error('加载订单失败:', error);
  }
});

// 获取会议室信息
// const selectedRoom = ref({});
const fetchRoomDetails = async (roomId) => {
  try {
    const response = await axios.get(`/rooms/${roomId}`);
    selectedRoom.value = response.data.data;
  } catch (error) {
    alert('获取会议室信息失败');
  }
};

// 开始倒计时
const startCountdown = () => {
  if (!createdTime.value) {
    remainingTime.value = '00:00';
    return;
  }

  countdownTimer = setInterval(() => {
    const now = new Date();
    const expireTime = new Date(createdTime.value.getTime() + 30 * 60 * 1000);
    const remaining = Math.max(0, Math.floor((expireTime - now) / 1000));

    const minutes = String(Math.floor(remaining / 60)).padStart(2, '0');
    const seconds = String(remaining % 60).padStart(2, '0');

    remainingTime.value = `${minutes}:${seconds}`;

    if (remaining <= 0 && isLocked.value) {
      clearInterval(countdownTimer);
      handleCancelOrder({ id: orderId.value }, false);
    }
  }, 1000);
};

const isPaying = ref(false);

// 支付逻辑
const handlePayment = async () => {
  const confirmMessage = `是否要支付 ${totalPrice.value} 元？`;
  if (!confirm(confirmMessage)) return;

  if (isPaying.value) return;
  isPaying.value = true;

  try {
    await axios.post(`/orders/${orderId.value}/pay`);
    alert('支付成功，订单已确认');
    router.push('/orders');
  } catch (error) {
    alert(error.response?.data?.error || '支付失败，请重试');
  } finally {
    isPaying.value = false;
  }
};

// 时间格式化：替换 T 为空格
const formatTime = (time) => {
  return time.replace('T', ' ');
};

// 自动取消订单
const handleCancelOrder = async (order) => {
  try {
    const response = await axios.post(`/orders/${order.id}/cancel`);
    alert('订单已超时取消');

    // 更新当前页面状态
    isLocked.value = false;
    orderStatus.value = '已取消';

    // 跳转回订单页
    router.push('/orders');

  } catch (error) {
    console.error('取消订单失败:', error);
    alert(error.response?.data?.message || '取消订单失败，请重试');
  }
};
</script>

<style scoped>
.order-info {
  margin: 20px 0;
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}
.payment-timer {
  color: #e53e3e;
  margin-bottom: 15px;
}

.header-panel {
  position: relative;
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
  text-align: center;
}
.booking-btn {
  position: absolute;
  right: 0;
  top: 0;
  background-color: #6b7280;
  color: white;
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.booking-btn:hover {
  background-color: #4b5563;
}
</style>